﻿using IcsSEMCtrl.Db;
using IcsSEMCtrl.Device.Observe;
using IcsSEMCtrl.Global;
using IcsSEMCtrl.Global.Device;
using IcsSEMCtrl.Service.Alarm;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Service.Material;
using IcsSEMCtrl.Util.Client;
using Lifter.Device;
using Lifter.Device.Dispatcher;
using Lifter.Device.Service.Alarm;
using Lifter.Device.Unit;
using Lifter.Global;
using Lifter.Global.Device;
using Lifter.Gui.Monitor.Popups;
using Lifter.Utility;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Device.Service.Alarm;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;
using static Lifter.Utility.Util;

namespace TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels
{
    /// <summary>
    /// add by yangshl
    /// 所有配置功能操作界面
    /// </summary>
    public partial class AllConfigControl : UserControl
    {
        private List<AlarmDao> AlarmsList = null;
        List<MenuManageDao> MenuList = new List<MenuManageDao>();
        List<PowerManageDao> PowerList = new List<PowerManageDao>();
        LifterAlarm lifterAlarm = LifterAlarm.GetLifterAlarm();
        List<string> AlarmTypeList = new List<string>();
        List<string> AlarmUseList = new List<string>();
        private LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
        /*        private bool MenuConfigCancelFlag = false;
                private bool AlarmConfigCancelFlag = false;
                private bool SignalConfigCancelFlag = false;*/
        Dictionary<string, int> PowerUserDict = new Dictionary<string, int>();
        Dictionary<string, int> ParentMenuDict = new Dictionary<string, int>();
        private string eqpInfoConfigDgvSelectName = "";
        private string unitInfoConfigDgvSelectName = "";
        private string unitInfoConfigDgvSelectEntityID = "";
        public AllConfigControl()
        {
            InitializeComponent();

            //初始化报警配置表
            InitShowAlarms();

            //初始化菜单配置表
            InitMenuDataGridView();

            //初始化权限配置
            InitPowerDataGridView();

            //初始化EQP参数配置表
            this.InitEqpInfoConfigDGV();

            //初始化Unit参数配置表
            this.InitUnitInfoConfigDGV();

            //初始化菜单权限节点表
            InitTreeNode();

            //初始化权限
            InitPowerMenu();

            //初始化Port配置信息数据表
            InitPortConfigDGV();

            this.AlarmStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            this.AlarmEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        private void InitPortConfigDGV()
        {
            InitPortInfoDGV();
            InitLocationUnitInfoDGV();
            InitSubSystemInfoDGV();
        }
        private void InitPortInfoDGV()
        {
            this.PortInfoDGV.DataSource = this.SearchLifterPortInfo("");
            this.PortInfoDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.PortInfoDGV.Columns[0].HeaderCell.Value = "PortID";
            this.PortInfoDGV.Columns[1].HeaderCell.Value = "传输方式";
            this.PortInfoDGV.Columns[2].HeaderCell.Value = "Port类型";
            this.PortInfoDGV.Columns[3].HeaderCell.Value = "Buffer数量";
            this.PortInfoDGV.Columns[4].HeaderCell.Value = "类型";
            this.PortInfoDGV.Columns[5].HeaderCell.Value = "是否组合";
            this.PortInfoDGV.Columns[6].HeaderCell.Value = "下一个位置";
            this.PortInfoDGV.Columns[7].HeaderCell.Value = "特殊楼层";
        }
        private void InitLocationUnitInfoDGV()
        {
            this.LocationUnitInfoDGV.DataSource = this.SearchLocUnitInfo("");
            this.LocationUnitInfoDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.LocationUnitInfoDGV.Columns[0].HeaderCell.Value = "PortID";
            this.LocationUnitInfoDGV.Columns[1].HeaderCell.Value = "PLCID";
            this.LocationUnitInfoDGV.Columns[2].HeaderCell.Value = "HostID";
        }
        private void InitSubSystemInfoDGV()
        {
            this.SubSystemInfoDGV.DataSource = this.SearchSubSystemInfo("");
            this.SubSystemInfoDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.SubSystemInfoDGV.Columns[0].HeaderCell.Value = "单元ID";
            this.SubSystemInfoDGV.Columns[1].HeaderCell.Value = "单元类型";
            this.SubSystemInfoDGV.Columns[2].HeaderCell.Value = "OwnerID";
            this.SubSystemInfoDGV.Columns[3].HeaderCell.Value = "Owner类型";
            this.SubSystemInfoDGV.Columns[4].HeaderCell.Value = "AssemblyName";
            this.SubSystemInfoDGV.Columns[5].HeaderCell.Value = "ClassName";
        }
        /// <summary>
		/// 初始化页面权限
		/// </summary>
		public void InitPowerMenu()
        {
            List<MenuDao> menusOperation = GetMenuByPower(LftSem.UserPower);
            updatePowerForm(menusOperation);
            InitTreeNode();
            /*            if (LftSem.UserPower.Equals(enumUserManage.Operation.ToString()))
                        {
                            List<MenuDao> menusOperation = GetMenuByPower(enumUserManage.Operation.ToString());
                            updatePowerForm(menusOperation);
                        }
                        else if (LftSem.UserPower.Equals(enumUserManage.Management.ToString()))
                        {
                            List<MenuDao> menusManagement = GetMenuByPower(enumUserManage.Management.ToString());
                            updatePowerForm(menusManagement);
                        }*/
        }
        private void updatePowerForm(List<MenuDao> menuDaos)
        {
            foreach (MenuDao menu in menuDaos)
            {
                if (menu.ENNAME.Equals("AlarmConfig"))
                {
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        this.Controls["UITBConfig"].Controls.Remove(this.AlarmConfig);
                    }
                    else
                    {
                        if (!this.Controls["UITBConfig"].Controls.Contains(this.AlarmConfig))
                        {
                            this.Controls["UITBConfig"].Controls.Add(this.AlarmConfig);
                        }
                        if (menu.MENUUSE.Equals("N"))
                        {
                            this.Controls["UITBConfig"].Controls["AlarmConfig"].Enabled = false;
                        }
                        else
                        {
                            this.Controls["UITBConfig"].Controls["AlarmConfig"].Enabled = true;
                        }
                    }
                }
                if (menu.ENNAME.Equals("MenuConfig"))
                {
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        this.Controls["UITBConfig"].Controls.Remove(this.MenuConfig);
                    }
                    else
                    {
                        if (!this.Controls["UITBConfig"].Controls.Contains(this.MenuConfig))
                        {
                            this.Controls["UITBConfig"].Controls.Add(this.MenuConfig);
                        }

                        if (menu.MENUUSE.Equals("N"))
                        {
                            this.Controls["UITBConfig"].Controls["MenuConfig"].Enabled = false;
                        }
                        else
                        {
                            this.Controls["UITBConfig"].Controls["MenuConfig"].Enabled = true;
                        }
                    }
                }
 /*               if (menu.ENNAME.Equals("SignalConfig"))
                {
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        this.Controls["UITBConfig"].Controls.Remove(this.SignalConfig);
                    }
                    else
                    {
                        if (!this.Controls["UITBConfig"].Controls.Contains(this.SignalConfig))
                        {
                            this.Controls["UITBConfig"].Controls.Add(this.SignalConfig);
                        }

                        if (menu.MENUUSE.Equals("N"))
                        {
                            this.Controls["UITBConfig"].Controls["SignalConfig"].Enabled = false;
                        }
                        else
                        {
                            this.Controls["UITBConfig"].Controls["SignalConfig"].Enabled = true;
                        }
                    }
                }*/
            }
        }
        private void DisableSelect(object sender, TabControlCancelEventArgs e)
        {
            e.Cancel = true;
        }
        private List<MenuDao> GetMenuByPower(string PowerName)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            List<MenuDao> menuLists = new List<MenuDao>();
            string sqlString = string.Format("SELECT USERMENU.ENNAME,USERMENU.CNNAME,USERMENUPOWER.MENUDISPLAY,USERMENUPOWER.MENUUSE" +
                                             " FROM USERMENU,USERMENUPOWER " +
                                             " WHERE USERMENU.ENNAME = USERMENUPOWER.MENUNAME " +
                                             " AND USERMENU.PARENTID = (SELECT ID FROM USERMENU WHERE USERMENU.ENNAME = '{0}') " +
                                             " AND USERMENUPOWER.POWERNAME = '{1}'", this.Name, PowerName);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                MenuDao menuDao = new MenuDao();
                menuDao.CNNAME = (string)sqlDataReader["CNNAME"];
                menuDao.ENNAME = (string)sqlDataReader["ENNAME"];
                menuDao.MENUDISPLAY = (string)sqlDataReader["MENUDISPLAY"];
                menuDao.MENUUSE = (string)sqlDataReader["MENUUSE"];
                menuLists.Add(menuDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return menuLists;
        }
        private class MenuDao
        {
            public string ENNAME { get; set; }
            public string CNNAME { get; set; }
            public string MENUDISPLAY { get; set; }
            public string MENUUSE { get; set; }
        }
        private void TCConfigMenu_Click(object sender, EventArgs e)
        {
        }
        private void InitShowAlarms()
        {
            //初始化获取所有的Alarm
            LifterAlarm lifterAlarm = LifterAlarm.GetLifterAlarm();
            AlarmsList = lifterAlarm.GetAllAlarm(null);
            this.InitDataGridView(AlarmsList);
            //初始化下拉框数据
            this.AlarmTypeList.Add("");
            this.AlarmTypeList.AddRange(Util.ObjectListToStringList(AlarmsList, "SUBSYSTEM").Distinct().ToList<string>());
            this.AlarmUseList.Add("");
            this.AlarmUseList.AddRange(Util.ObjectListToStringList(AlarmsList, "IS_HOST_REPORT").Distinct().ToList<string>());
            this.cbAddAlarmType.DataSource = AlarmTypeList;
            this.cbAddAlarmUse.DataSource = AlarmUseList;
        }
        /// <summary>
        /// add by yangshl
        /// 修改表格式
        /// </summary>
        /// <param name="AlarmsList"></param>
        private void InitDataGridView(List<AlarmDao> AlarmsList)
        {
            this.AlarmDataGridView.DataSource = AlarmsList;
            AlarmDataGridView.Columns[0].HeaderCell.Value = "警报ID";
            AlarmDataGridView.Columns[1].HeaderCell.Value = "警报代码";
            AlarmDataGridView.Columns[2].HeaderCell.Value = "报警内容";
            AlarmDataGridView.Columns[2].Width = 400;
            AlarmDataGridView.Columns[3].HeaderCell.Value = "警报类型";
            AlarmDataGridView.Columns[3].Width = 150;
            AlarmDataGridView.Columns[4].HeaderCell.Value = "是否启用";
            AlarmDataGridView.Columns[5].HeaderCell.Value = "报警原因";
            AlarmDataGridView.Columns[5].Width = 400;
            AlarmDataGridView.Columns[6].HeaderCell.Value = "解决方案";
            AlarmDataGridView.Columns[6].Width = 400;
            AlarmDataGridView.Columns[7].HeaderCell.Value = "创建时间";

            //设置分页信息
            //设置分页控件总数
            AlarmPagination.TotalCount = AlarmsList.Count();
            //设置分页控件每页数量
            AlarmPagination.PageSize = Convert.ToInt32(this.PageSize.Value);
            AlarmPagination.ActivePage = 1;
        }
        /// <summary>
        /// 2023/2/17 add by yangshl
        /// alarm查询点击事件
        /// 跟据页面输入的查询条件，匹配查询ALARM表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAlarm_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> Conditions = new Dictionary<string, string>();

            //获取前端输入框内容
            string SelectAlarmCode = this.tbSelectAlarmCode.Text;
            string AlarmType = this.cbAlarmType.Text;
            string AlarmUse = this.cbAlarmUse.Text;
            string StartTime = this.AlarmStartTime.Text;
            string EndTime = this.AlarmEndTime.Text;
            if (!string.IsNullOrWhiteSpace(SelectAlarmCode))
            {
                Conditions.Add("ALCD", SelectAlarmCode);
            }
            if (!string.IsNullOrWhiteSpace(AlarmType))
            {
                Conditions.Add("SUBSYSTEM", AlarmType);
            }
            if (!string.IsNullOrWhiteSpace(AlarmUse))
            {
                Conditions.Add("IS_HOST_REPORT", AlarmUse);
            }
            if (!string.IsNullOrWhiteSpace(StartTime))
            {
                Conditions.Add("StartTime", StartTime);
            }
            if (!string.IsNullOrWhiteSpace(EndTime))
            {
                Conditions.Add("EndTime", EndTime);
            }

            //调用查询方法
            AlarmsList = lifterAlarm.GetAllAlarm(Conditions);
            this.InitDataGridView(AlarmsList);
        }

        private void cbAlarmType_DropDown(object sender, EventArgs e)
        {
            this.cbAlarmType.DataSource = AlarmTypeList;
        }

        private void cbAlarmUse_DropDown(object sender, EventArgs e)
        {
            this.cbAlarmUse.DataSource = AlarmUseList;
        }

        //pageIndex：第几页，和界面对应，从1开始，取数据可能要用pageIndex - 1
        //count：单页数据量，也就是PageSize值
        private void AlarmPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (AlarmPagination.TotalCount >= pageIndex * count)
            {
                this.AlarmDataGridView.DataSource = AlarmsList.GetRange((pageIndex - 1) * count, count);
            }
            else
            {
                this.AlarmDataGridView.DataSource = AlarmsList.GetRange((pageIndex - 1) * count, (AlarmPagination.TotalCount - ((pageIndex - 1) * count)));
            }
        }
        /// <summary>
        /// add by yangshl
        /// 设置分页功能单页显示数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void PageSize_ValueChanged(object sender, int value)
        {
            //设置分页信息
            //设置分页控件总数
            AlarmPagination.TotalCount = AlarmsList.Count();
            //设置分页控件每页数量
            AlarmPagination.PageSize = Convert.ToInt32(this.PageSize.Value);
            AlarmPagination.ActivePage = 1;
        }
        /// <summary>
        /// add by yangshl
        /// 创建Alarm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddAlarm_Click(object sender, EventArgs e)
        {
            //获取页面输入框数据，并存入字典里面
            Dictionary<string, string> AlarmDict = new Dictionary<string, string>();
            AlarmDict.Add("ALID", this.tbAddAlarmID.Text);
            AlarmDict.Add("ALCD", this.tbAddAlarmCode.Text);
            AlarmDict.Add("ALTX", this.tbAddAlarmText.Text);
            AlarmDict.Add("SUBSYSTEM", this.cbAddAlarmType.Text);
            AlarmDict.Add("IS_HOST_REPORT", this.cbAddAlarmUse.Text);
            AlarmDict.Add("CREATETIME", Util.GetNowDateTimeString(dateTimeFormat.yyyy_MM_ddHHmmss));
            AlarmDict.Add("CAUSE", this.tbAddAlarmCause.Text);
            AlarmDict.Add("SOLUTION", this.tbAlarmSolution.Text);
            //判断输入框是否为空
            if (this.CheckData())
            {
                //创建alarm
                this.lifterAlarm.AddAlarm(AlarmDict);
            }
        }
        /// <summary>
        /// 校验输入框是否为空
        /// </summary>
        private bool CheckData()
        {
            bool flag = true;
            if (this.tbAddAlarmID.Text == "")
            {
                PopupNotice.TipsPopups("警报ID输入不能为空", "Alarm ID input cannot be empty");
                flag = false;
            }
            else if (this.tbAddAlarmCode.Text == "")
            {
                PopupNotice.TipsPopups("警报代码输入不能为空", "Alarm Code input cannot be empty");
                flag = false;
            }
            else if (this.cbAddAlarmType.Text == "")
            {
                PopupNotice.TipsPopups("警报类型输入不能为空", "Alarm Type input cannot be empty");
                flag = false;
            }
            else if (this.tbAddAlarmText.Text == "")
            {

                PopupNotice.TipsPopups("警报内容输入不能为空", "Alarm Content input cannot be empty");
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 修改Alarm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btModifyAlarm_Click(object sender, EventArgs e)
        {
            //获取页面输入框数据，并存入字典里面
            Dictionary<string, string> AlarmDict = new Dictionary<string, string>();
            AlarmDict.Add("ALID", this.tbAddAlarmID.Text);
            AlarmDict.Add("ALCD", this.tbAddAlarmCode.Text);
            AlarmDict.Add("ALTX", this.tbAddAlarmText.Text);
            AlarmDict.Add("SUBSYSTEM", this.cbAddAlarmType.Text);
            AlarmDict.Add("IS_HOST_REPORT", this.cbAddAlarmUse.Text);
            AlarmDict.Add("CREATETIME", Util.GetNowDateTimeString(dateTimeFormat.yyyy_MM_ddHHmmss));
            AlarmDict.Add("CAUSE", this.tbAddAlarmCause.Text);
            //判断输入框是否为空
            if (this.CheckData())
            {
                //修改alarm
                this.lifterAlarm.ModifyAlarm(AlarmDict);
            }
        }

        /// <summary>
        /// 删除Alarm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDeleteAlarm_Click(object sender, EventArgs e)
        {
            //判断输入框是否为空
            if (this.tbAddAlarmCode.Text != "")
            {
                //删除alarm
                this.lifterAlarm.DeleteAlarm(this.tbAddAlarmCode.Text);
            }
        }

        private void Addobservable_Click(object sender, EventArgs e)
        {
            AccessType accessType = AccessType.IN;
            ElementType elementType = ElementType.EQUIPMENT;
            DataType dataType = DataType.BOOLEAN;
            bool isMonitoring = false;
            switch (this.tbelementType.Text)
            {
                case "Equipment":
                    elementType = ElementType.EQUIPMENT;
                    break;
                case "SubSystem":
                    elementType = ElementType.SUBSYSTEM;
                    break;
                case "Module":
                    elementType = ElementType.MODULE;
                    break;
            }
            switch (this.tbaccessType.Text)
            {
                case "In":
                    accessType = AccessType.IN;
                    break;
                case "Out":
                    accessType = AccessType.OUT;
                    break;
                case "In_Out":
                    accessType = AccessType.IN_OUT;
                    break;
            }
            switch (this.tbdataType.Text)
            {
                case "Boolean":
                    dataType = DataType.BOOLEAN;
                    break;
                case "Byte":
                    dataType = DataType.BYTE;
                    break;
                case "Short":
                    dataType = DataType.SHORT;
                    break;
                case "String":
                    dataType = DataType.STRING;
                    break;
            }
            switch (this.tbisMonitoring.Text)
            {
                case "T":
                    isMonitoring = true;
                    break;
                case "F":
                    isMonitoring = false;
                    break;
            }
            string connectionInfoString = string.Concat("DEVICE_TYPE=", this.tbobservableType.Text, ",", "ADDRESS_NO=", this.tbobservableAddr.Text);
            try
            {
                Observable value = Observable.CreateObservable(this.tbelementId.Text, elementType, this.tbobservableId.Text, this.tbobservablePath.Text, accessType, dataType, Convert.ToDouble(this.tbmin.Text), Convert.ToDouble(this.tbmax.Text), 1, isMonitoring, connectionInfoString, this.tbdescription.Text, true, "..", "..");
                PopupNotice.DialogPopups("点位添加成功", "Successfully added point", enumPopupsType.OK);
            }
            catch (Exception ex)
            {
                PopupNotice.DialogPopups("点位添加失败", "Failed added point", enumPopupsType.Error);
                throw ex;
            }
        }

        #region 权限管理功能

        /// <summary>
        /// 添加权限功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddPower_Click(object sender, EventArgs e)
        {
            string PowerName = this.tbPowerName.Text;
            string PowerLevel = this.tbPowerLevel.Text;
            string desc = this.tbPowerDescription.Text;
            if (this.tbPowerName.Text.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            if (this.tbPowerLevel.Text.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限不能为空", "Power cannot be empty");
                return;
            }
            if (this.SeachPowerAll(tbPowerName.Text).Count <= 0)
            {
                //添加权限数据
                this.AddPower(PowerName, Convert.ToInt32(PowerLevel), desc);
                //刷新列表
                DGVPowers.DataSource = this.SeachPowerAll("");
                this.ClearInputData();
            }
            else
            {
                PopupNotice.DialogPopups("添加失败，当前权限数据已存在，请检查！！！", "Adding failed. The current permission data already exists. Please check!!!", enumPopupsType.Error);
            }
        }
        /// <summary>
        /// 修改权限功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btModifyPower_Click(object sender, EventArgs e)
        {
            string PowerName = this.tbPowerName.Text;
            string PowerLevel = this.tbPowerLevel.Text;
            string desc = this.tbPowerDescription.Text;
            if (PowerName.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            List<PowerManageDao> TmpList = this.SeachPowerAll(tbPowerName.Text);
            if (TmpList.Count > 0)
            {
                if (PowerLevel.IsNullOrEmpty())
                {
                    PowerLevel = TmpList[0].POWER.ToString();
                }
                if (desc.IsNullOrEmpty())
                {
                    desc = TmpList[0].DESCRIPTION;
                }
                //修改权限数据
                this.ModifyPower(PowerName, Convert.ToInt32(PowerLevel), desc);
                //刷新列表
                DGVPowers.DataSource = this.SeachPowerAll("");
                this.ClearInputData();
            }
            else
            {
                PopupNotice.DialogPopups("修改失败，当前权限数据不存在，请检查！！！", "Modification failed. The current permission data does not exist. Please check!!!", enumPopupsType.Error);
            }
        }
        /// <summary>
        /// 删除权限功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDeletePower_Click(object sender, EventArgs e)
        {
            string PowerName = this.tbPowerName.Text;
            string PowerLevel = this.tbPowerLevel.Text;
            string desc = this.tbPowerDescription.Text;
            if (PowerName.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            List<PowerManageDao> TmpList = this.SeachPowerAll(PowerName);
            if (TmpList.Count > 0)
            {
                //删除权限数据
                this.DeletePower(PowerName);
                //刷新列表
                DGVPowers.DataSource = this.SeachPowerAll("");
                this.ClearInputData();
            }
            else
            {
                PopupNotice.DialogPopups("删除失败，当前权限数据不存在，请检查！！！", "Delete failed. The current power data does not exist. Please check!!!", enumPopupsType.Error);
            }
        }
        /// <summary>
        /// 查询权限功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSearchPower_Click(object sender, EventArgs e)
        {
            DGVPowers.DataSource = SeachPowerAll(this.tbPowerName.Text);
            this.ClearInputData();
        }
        /// <summary>
        ///查询权限表数据,返回权限list数据
        /// </summary>
        private List<PowerManageDao> SeachPowerAll(string powerName)
        {
            string sqlString = "SELECT * FROM USERPOWER";
            if (!powerName.IsNullOrEmpty())
            {
                sqlString = string.Format("SELECT * FROM USERPOWER WHERE POWERNAME = '{0}'", powerName);
            }
            DBConnection dBConnection = DBControl.GetConnection();

            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);

            List<PowerManageDao> powerLists = new List<PowerManageDao>();
            while (sqlDataReader.Read())
            {
                PowerManageDao powerManageDao = new PowerManageDao();
                powerManageDao.ID = (int)sqlDataReader["ID"];
                powerManageDao.POWERNAME = (string)sqlDataReader["POWERNAME"];
                powerManageDao.POWER = (int)sqlDataReader["POWER"];
                powerManageDao.DESCRIPTION = (string)sqlDataReader["DESCRIPTION"];
                powerManageDao.MODIFYTIME = (DateTime)sqlDataReader["MODIFYTIME"];

                powerLists.Add(powerManageDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return powerLists;
        }

        private void AddPower(string PowerName, int Power, string desc)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("INSERT INTO USERPOWER VALUES(N'{0}',{1},N'{2}','{3}')", PowerName, Power, desc, DateTime.Now);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("添加成功", "Add successfully", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("添加失败,请检查！！！", "Add failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        /// <summary>
        /// 修改权限数据
        /// </summary>
        /// <param name="PowerName"></param>
        /// <param name="Power"></param>
        /// <param name="desc"></param>
        private void ModifyPower(string PowerName, int Power, string desc)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("UPDATE USERPOWER SET  POWER = {1}, DESCRIPTION = '{2}', MODIFYTIME = '{3}' WHERE POWERNAME = '{0}'", PowerName, Power, desc, DateTime.Now);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("修改成功", "Successfully modified", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("修改失败,请检查！！！", "Modification failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        /// <summary>
        /// 删除权限数据
        /// </summary>
        /// <param name="PowerName"></param>
        /// <param name="Power"></param>
        /// <param name="desc"></param>
        private void DeletePower(string PowerName)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("DELETE FROM USERPOWER WHERE POWERNAME = '{0}'", PowerName);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("删除成功", "Successfully deleted", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("删除失败,请检查！！！", "Delete failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        /// <summary>
        /// 清除输入框的数据
        /// </summary>
        private void ClearInputData()
        {
            this.tbPowerName.Text = "";
            this.tbPowerLevel.Text = "";
            this.tbPowerDescription.Text = "";
        }
        /// <summary>
        /// 权限表实体类
        /// </summary>
        public class PowerManageDao
        {
            //权限ID
            public int ID { get; set; }
            //权限名
            public string POWERNAME { get; set; }
            public int POWER { get; set; }
            //权限描述
            public string DESCRIPTION { get; set; }
            //修改时间
            public DateTime MODIFYTIME { get; set; }
        }
        #endregion

        #region 菜单管理功能
        /// <summary>
        /// 添加菜单功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddMenu_Click(object sender, EventArgs e)
        {
            string ParentMenu = this.cbParentMenu.Text;
            string CNMenu = this.tbCNMenu.Text;
            string ENMenu = this.tbENMenu.Text;
            string MenuType = this.cbMenuType.Text;
            if (CNMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单中文名不能为空", "The Chinese name of the menu cannot be empty");
                return;
            }
            if (ENMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单英文名不能为空", "The menu English name cannot be empty");
                return;
            }
            if (MenuType.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("类型不能为空", "Type cannot be empty");
                return;
            }
            List<string> conditions = new List<string>() { "", "", "", "" };

            conditions[1] = CNMenu;
            //判断是否已存在菜单
            if (this.SearchMenuAll(conditions).Count > 0)
            {
                PopupNotice.DialogPopups("添加失败，菜单已经存在,请检查！！！", "Adding failed, menu already exists, please check!!!", enumPopupsType.Error);
                return;
            }
            else
            {
                if (ParentMenu.IsNullOrEmpty())
                {

                    conditions[0] = "-1";
                }
                else
                {
                    conditions[0] = this.tbParentID.Text;
                }
                conditions[2] = ENMenu;
                conditions[3] = MenuType;
                this.AddMenu(conditions);
                //刷新页面
                this.ShowMenuDGV(this.SearchMenuAll(new List<string>()));
                this.ClearMenuInputData();
            }
        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        public void AddMenu(List<string> AddData)
        {
            if (AddData != null && AddData.Count > 0)
            {
                try
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    string sqlString = string.Format("INSERT INTO USERMENU VALUES({0},N'{1}','{2}','{3}','{4}')", Convert.ToInt32(AddData[0]), AddData[1], AddData[2], DateTime.Now, AddData[3]);
                    int returnCode = dBConnection.ExecuteUpdate(sqlString);
                    if (returnCode > 0)
                    {
                        PopupNotice.DialogPopups("添加成功", "Add successfully", enumPopupsType.OK);
                    }
                    else
                    {
                        PopupNotice.DialogPopups("添加失败,请检查！！！", "Add failed, please check!!!", enumPopupsType.Error);
                    }
                    DBControl.RemoveDBConection(dBConnection);
                }
                catch (Exception ex)
                {
                    UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
                }
            }
        }
        /// <summary>
        /// 修改菜单功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btModifyMenu_Click(object sender, EventArgs e)
        {
            string ParentMenu = this.cbParentMenu.Text;
            string CNMenu = this.tbCNMenu.Text;
            string ENMenu = this.tbENMenu.Text;
            string MenuType = this.cbMenuType.Text;
            if (CNMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单名不能为空", "The menu name cannot be empty");
                return;
            }
            List<string> ConditionList = new List<string>(4) { "", "", "", "" };
            ConditionList[1] = CNMenu;
            List<MenuManageDao> TmpList = this.SearchMenuAll(ConditionList);

            if (TmpList.Count > 0)
            {
                if (ParentMenu.IsNullOrEmpty())
                {
                    ParentMenu = TmpList[0].PARENTID.ToString();
                }
                if (ENMenu.IsNullOrEmpty())
                {
                    ENMenu = TmpList[0].ENNAME;
                }
                if (MenuType.IsNullOrEmpty())
                {
                    MenuType = TmpList[0].MENUTYPE;
                }
                //修改权限数据
                this.ModifyMenu(Convert.ToInt32(ParentMenu), CNMenu, ENMenu, MenuType);
                //刷新列表
                this.ShowMenuDGV(this.SearchMenuAll(new List<string>()));
                this.ClearMenuInputData();
            }
            else
            {
                PopupNotice.DialogPopups("修改失败，当前菜单数据不存在，请检查！！！", "Modification failed. The current menu data does not exist. Please check!!!", enumPopupsType.Error);
            }
        }
        /// <summary>
        /// 删除菜单功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDeleteMenu_Click(object sender, EventArgs e)
        {
            string CNMenu = this.tbCNMenu.Text;
            if (CNMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单名不能为空", "The menu name cannot be empty");
                return;
            }
            List<string> conditions = new List<string>(4) { "", "", "", "" };
            conditions[1] = CNMenu;
            List<MenuManageDao> TmpList = this.SearchMenuAll(conditions);
            if (TmpList.Count > 0)
            {
                //删除权限数据
                this.DeleteMenu(CNMenu);
                //刷新列表
                this.ShowMenuDGV(this.SearchMenuAll(new List<string>()));
                this.ClearMenuInputData();
            }
            else
            {
                PopupNotice.DialogPopups("删除失败，当前菜单数据不存在，请检查！！！", "Delete failed. The current menu data does not exist. Please check!!!", enumPopupsType.Error);
            }
        }
        /// <summary>
        /// 查询菜单功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSearchMenu_Click(object sender, EventArgs e)
        {
            List<string> conditionLists = new List<string>();

            conditionLists.Add(this.tbParentID.Text);
            conditionLists.Add(this.tbCNMenu.Text);
            conditionLists.Add(this.tbENMenu.Text);
            conditionLists.Add(this.cbMenuType.Text);
            MenuList = this.SearchMenuAll(conditionLists);
            this.ShowMenuDGV(MenuList);
            this.ClearMenuInputData();
        }
        public List<string> GetParentMenu(string type)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            List<string> ParentMenuList = new List<string>();
            string sqlString = string.Format("SELECT {0} FROM USERMENU WHERE PARENTID < 0", type);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                ParentMenuList.Add((string)sqlDataReader[type]);
            }
            return ParentMenuList;
        }
        /// <summary>
        /// 查询所有的菜单数据
        /// </summary>
        /// <returns></returns>
        public List<MenuManageDao> SearchMenuAll(List<string> conditions)
        {
            bool flag = true;
            StringBuilder sqlString = new StringBuilder();
            sqlString.Append("SELECT * FROM USERMENU");
            if (conditions.Count > 0 && !conditions[0].IsNullOrEmpty())
            {
                string sqlMsg = string.Format(" WHERE PARENTID = '{0}'", conditions[0]);
                sqlString.Append(sqlMsg);
                flag = false;
            }
            if (conditions.Count > 1 && !conditions[1].IsNullOrEmpty())
            {
                if (flag)
                {
                    string sqlMsg = string.Format(" WHERE CNNAME = N'{0}'", conditions[1]);
                    sqlString.Append(sqlMsg);
                    flag = false;
                }
                else
                {
                    string sqlMsg = string.Format(" AND CNNAME = N'{0}'", conditions[1]);
                    sqlString.Append(sqlMsg);
                }
            }
            if (conditions.Count > 2 && !conditions[2].IsNullOrEmpty())
            {
                if (flag)
                {
                    string sqlMsg = string.Format(" WHERE ENNAME = '{0}'", conditions[2]);
                    sqlString.Append(sqlMsg);
                    flag = false;
                }
                else
                {
                    string sqlMsg = string.Format(" AND ENNAME = '{0}'", conditions[2]);
                    sqlString.Append(sqlMsg);
                }
            }
            if (conditions.Count > 3 && !conditions[3].IsNullOrEmpty())
            {
                if (flag)
                {
                    string sqlMsg = string.Format(" WHERE MENUTYPE = '{0}'", conditions[3]);
                    sqlString.Append(sqlMsg);
                }
                else
                {
                    string sqlMsg = string.Format(" AND MENUTYPE = '{0}'", conditions[3]);
                    sqlString.Append(sqlMsg);
                }
            }
            DBConnection dBConnection = DBControl.GetConnection();
            List<MenuManageDao> menuManageDaoLists = new List<MenuManageDao>();
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString.ToString());
            while (sqlDataReader.Read())
            {
                MenuManageDao menuManageDao = new MenuManageDao();
                menuManageDao.ID = (int)sqlDataReader["ID"];
                menuManageDao.PARENTID = (int)sqlDataReader["PARENTID"];
                menuManageDao.CNNAME = (string)sqlDataReader["CNNAME"];
                menuManageDao.ENNAME = (string)sqlDataReader["ENNAME"];
                menuManageDao.MODIFYTIME = (DateTime)sqlDataReader["MODIFYTIME"];
                menuManageDao.MENUTYPE = (string)sqlDataReader["MENUTYPE"];

                menuManageDaoLists.Add(menuManageDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            MenuList = menuManageDaoLists;
            return menuManageDaoLists;
        }
        private void InitMenuDataGridView()
        {
            MenuList = this.SearchMenuAll(new List<string>());
            this.ShowMenuDGV(MenuList);
            LoadCbData();
            this.DGVMenu.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            DGVMenu.Columns[0].HeaderCell.Value = "菜单ID";
            DGVMenu.Columns[1].HeaderCell.Value = "父级菜单ID";
            DGVMenu.Columns[2].HeaderCell.Value = "菜单中文名";
            DGVMenu.Columns[3].HeaderCell.Value = "菜单英文名";
            DGVMenu.Columns[4].HeaderCell.Value = "修改时间";
            DGVMenu.Columns[5].HeaderCell.Value = "菜单类型";


        }
        public void LoadCbData()
        {
            List<string> parentMenu = new List<string>();
            List<string> MenuType = new List<string>();
            parentMenu.Add("");
            parentMenu.AddRange(this.GetParentMenu("ENNAME").Distinct());
            MenuType.Add("");
            MenuType.AddRange(this.GetParentMenu("MENUTYPE").Distinct());
            this.cbParentMenu.DataSource = parentMenu;
            this.cbMenuType.DataSource = MenuType;
        }

        private void cbParentMenu_DropDown(object sender, EventArgs e)
        {
            LoadCbData();
        }
        private void InitPowerDataGridView()
        {
            PowerList = this.SeachPowerAll("");
            DGVPowers.DataSource = PowerList;

            DGVUserPower.DataSource = PowerList;
            this.DGVPowers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            DGVPowers.Columns[0].HeaderCell.Value = "权限ID";
            DGVPowers.Columns[1].HeaderCell.Value = "权限名";
            DGVPowers.Columns[2].HeaderCell.Value = "权限等级";
            DGVPowers.Columns[3].HeaderCell.Value = "描述";
            DGVPowers.Columns[4].HeaderCell.Value = "修改时间";

            DGVUserPower.Columns[0].HeaderCell.Value = "权限ID";
            DGVUserPower.Columns[1].HeaderCell.Value = "权限名";
            DGVUserPower.Columns[2].HeaderCell.Value = "权限等级";
            DGVUserPower.Columns[2].Width = 400;
            DGVUserPower.Columns[3].HeaderCell.Value = "描述";
            DGVUserPower.Columns[3].Width = 150;
            DGVUserPower.Columns[4].HeaderCell.Value = "修改时间";

        }
        /// <summary>
        /// 初始化EQP配置信息表
        /// </summary>
        private void InitEqpInfoConfigDGV()
        {
            this.eqpInfoConfigDgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.eqpInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.eqpInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.eqpInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.eqpInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.eqpInfoConfigDgv.Columns[0].HeaderText = "单元ID";
            this.eqpInfoConfigDgv.Columns[1].HeaderText = "参数名";
            this.eqpInfoConfigDgv.Columns[2].HeaderText = "参数值";
            this.eqpInfoConfigDgv.Columns[3].HeaderText = "描述";
            this.LoadAllEqpInfoConfig();
        }
        /// <summary>
        /// 加载所有的EQP配置信息
        /// </summary>
        private void LoadAllEqpInfoConfig()
        {
            string sqlString = "SELECT * FROM EQUIPMENTUDPROPERTY";
            DBConnection dBConnection = DBControl.GetConnection();
            SqlDataReader sqlDataReader = null;
            try
            {
                sqlDataReader = dBConnection.ExecuteQuery(sqlString);
                List<UDPropertyDao> propertyDaos = new List<UDPropertyDao>();
                while (sqlDataReader.Read())
                {
                    UDPropertyDao uDPropertyDao = new UDPropertyDao();
                    uDPropertyDao.EntityID = sqlDataReader["ENTITYID"].ToString();
                    uDPropertyDao.Name = sqlDataReader["NAME"].ToString();
                    uDPropertyDao.Value = sqlDataReader["VALUE"].ToString();
                    uDPropertyDao.Desc = sqlDataReader.IsDBNull(3) ? "" : sqlDataReader["DESCRIBE"].ToString();
                    propertyDaos.Add(uDPropertyDao);
                }
                //加载显示dgv表数据
                this.ShowEqpInfoConfig(propertyDaos);
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在加载所有的EQP配置信息时报错",ex);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
        }
        private void ShowEqpInfoConfig(List<UDPropertyDao> uDPropertyDaos)
        {
            if (uDPropertyDaos != null && uDPropertyDaos.Count > 0)
            {
                int index = 0;
                this.eqpInfoConfigDgv.RowCount = uDPropertyDaos.Count();
                foreach (UDPropertyDao item in uDPropertyDaos)
                {
                    this.eqpInfoConfigDgv.Rows[index].Cells[0].Value = item.EntityID;
                    this.eqpInfoConfigDgv.Rows[index].Cells[1].Value = item.Name;
                    this.eqpInfoConfigDgv.Rows[index].Cells[2].Value = item.Value;
                    this.eqpInfoConfigDgv.Rows[index].Cells[3].Value = item.Desc;
                    index++;
                }
            }
        }
        /// <summary>
        /// 初始化Unit配置信息表
        /// </summary>
        private void InitUnitInfoConfigDGV()
        {
            this.unitInfoConfigDgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.unitInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.unitInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.unitInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.unitInfoConfigDgv.Columns.Add(new DataGridViewTextBoxColumn());
            this.unitInfoConfigDgv.Columns[0].HeaderText = "单元ID";
            this.unitInfoConfigDgv.Columns[1].HeaderText = "参数名";
            this.unitInfoConfigDgv.Columns[2].HeaderText = "参数值";
            this.unitInfoConfigDgv.Columns[3].HeaderText = "描述";
            this.LoadAllUnitInfoConfig();
        }
        /// <summary>
        /// 加载所有的Unit配置信息
        /// </summary>
        private void LoadAllUnitInfoConfig()
        {
            string sqlString = "SELECT * FROM SUBSYSTEMUDPROPERTY";
            DBConnection dBConnection = DBControl.GetConnection();
            SqlDataReader sqlDataReader = null;
            try
            {
                sqlDataReader = dBConnection.ExecuteQuery(sqlString);
                List<UDPropertyDao> propertyDaos = new List<UDPropertyDao>();
                while (sqlDataReader.Read())
                {
                    UDPropertyDao uDPropertyDao = new UDPropertyDao();
                    uDPropertyDao.EntityID = sqlDataReader["ENTITYID"].ToString();
                    uDPropertyDao.Name = sqlDataReader["NAME"].ToString();
                    uDPropertyDao.Value = sqlDataReader["VALUE"].ToString();
                    uDPropertyDao.Desc = sqlDataReader.IsDBNull(3) ? "" : sqlDataReader["DESCRIBE"].ToString();
                    propertyDaos.Add(uDPropertyDao);
                }
                this.ShowUnitInfoConfig(propertyDaos);
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在加载所有的Unit配置信息时报错", ex);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
        }
        private void ShowUnitInfoConfig(List<UDPropertyDao> uDPropertyDaos)
        {
            if (uDPropertyDaos != null && uDPropertyDaos.Count > 0)
            {
                int index = 0;
                this.unitInfoConfigDgv.RowCount = uDPropertyDaos.Count();
                foreach (UDPropertyDao item in uDPropertyDaos)
                {
                    this.unitInfoConfigDgv.Rows[index].Cells[0].Value = item.EntityID;
                    this.unitInfoConfigDgv.Rows[index].Cells[1].Value = item.Name;
                    this.unitInfoConfigDgv.Rows[index].Cells[2].Value = item.Value;
                    this.unitInfoConfigDgv.Rows[index].Cells[3].Value = item.Desc;
                    index++;
                }
            }
        }
        private void ShowMenuDGV(List<MenuManageDao> menuList)
        {
            this.DGVMenu.DataSource = menuList;
            //设置分页信息
            //设置分页控件总数
            MenuDataPagination.TotalCount = menuList.Count();
            //设置分页控件每页数量
            MenuDataPagination.PageSize = Convert.ToInt32(this.MenuDataSize.Value);
            MenuDataPagination.ActivePage = 1;
        }
        private void MenuDataPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (MenuDataPagination.TotalCount >= pageIndex * count)
            {
                this.DGVMenu.DataSource = MenuList.GetRange((pageIndex - 1) * count, count);
            }
            else
            {
                this.DGVMenu.DataSource = MenuList.GetRange((pageIndex - 1) * count, (MenuDataPagination.TotalCount - ((pageIndex - 1) * count)));
            }
        }

        private void MenuDataSize_ValueChanged(object sender, int value)
        {
            //设置分页信息
            //设置分页控件总数
            MenuDataPagination.TotalCount = MenuList.Count();
            //设置分页控件每页数量
            MenuDataPagination.PageSize = Convert.ToInt32(this.MenuDataSize.Value);
            MenuDataPagination.ActivePage = 1;
        }
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="parentID"></param>
        /// <param name="cnName"></param>
        /// <param name="enNAME"></param>
        /// <param name="menuType"></param>
        private void ModifyMenu(int parentID, string cnName, string enNAME, string menuType)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("UPDATE USERMENU SET  PARENTID = '{0}', ENNAME = '{1}', MODIFYTIME = '{2}' , MENUTYPE = {3} WHERE CNNAME = N'{4}'", parentID, enNAME, DateTime.Now, menuType, cnName);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("修改成功", "Successfully modified", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("修改失败,请检查！！！", "Modification failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        private void DeleteMenu(string cnMenu)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("DELETE FROM USERMENU WHERE CNNAME = N'{0}'", cnMenu);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("删除成功", "Successfully deleted", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("删除失败,请检查！！！", "Delete failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        private void ClearMenuInputData()
        {
            this.cbParentMenu.Text = "";
            this.tbParentID.Text = "";
            this.tbCNMenu.Text = "";
            this.tbENMenu.Text = "";
            this.cbMenuType.Text = "";
        }
        public class MenuManageDao
        {
            public int ID { get; set; }
            public int PARENTID { get; set; }
            public string CNNAME { get; set; }
            public string ENNAME { get; set; }
            public DateTime MODIFYTIME { get; set; }
            public string MENUTYPE { get; set; }
        }
        #endregion

        #region 菜单权限配置功能
        /// <summary>
        /// 单击单元格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DGVUserPower_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            UpdateDisplayTreeStatus(e);
            UpdateUseTreeStatus(e);
        }
        /// <summary>
        /// 更新显示节点树的节点选择状态
        /// </summary>
        private void UpdateDisplayTreeStatus(DataGridViewCellEventArgs e)
        {
            this.InitDisplayTreeNode();
            DBConnection dBConnection = DBControl.GetConnection();
            if (e.RowIndex < 0)
            {
                return;
            }
            string PowerName = DGVUserPower.Rows[e.RowIndex].Cells[1].Value.ToString();
            string sqlString = string.Format("SELECT USERMENU.CNNAME,USERMENU.ENNAME FROM USERMENU,USERPOWER,USERMENUPOWER " +
                                             " WHERE USERMENU.ENNAME = USERMENUPOWER.MENUNAME " +
                                             " AND USERPOWER.POWERNAME = USERMENUPOWER.POWERNAME " +
                                             " AND USERMENUPOWER.MENUDISPLAY = 'Y'" +
                                             " AND USERPOWER.POWERNAME = '{0}'", PowerName);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            List<string> menuNameList = new List<string>();
            while (sqlDataReader.Read())
            {
                if (this.LftSem.LanguageType.Equals("zh"))
                {
                    menuNameList.Add((string)sqlDataReader["CNNAME"]);
                }
                else
                {
                    menuNameList.Add((string)sqlDataReader["ENNAME"]);
                }
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            //获取页面tvMenuDisplay控件上的所有节点
            List<TreeNode> trees = new List<TreeNode>();
            foreach (TreeNode item in this.tvMenuDisplay.Nodes)
            {
                if (item.Nodes.Count > 0)
                {
                    foreach (TreeNode tree in item.Nodes)
                    {
                        trees.Add(tree);
                    }
                }
                trees.Add(item);
            }
            foreach (TreeNode parentNode in trees)
            {
                foreach (string name in menuNameList)
                {
                    if (name.Equals(parentNode.Text))
                    {
                        parentNode.Checked = true;
                    }
                }
            }
        }
        /// <summary>
        /// 更新使用节点树的节点选择状态
        /// </summary>
        private void UpdateUseTreeStatus(DataGridViewCellEventArgs e)
        {
            this.InitUseTreeNode();
            DBConnection dBConnection = DBControl.GetConnection();
            if (e.RowIndex < 0)
            {
                return;
            }
            string PowerName = DGVUserPower.Rows[e.RowIndex].Cells[1].Value.ToString();
            string sqlString = string.Format("SELECT USERMENU.CNNAME,USERMENU.ENNAME FROM USERMENU,USERPOWER,USERMENUPOWER " +
                                             " WHERE USERMENU.ENNAME = USERMENUPOWER.MENUNAME " +
                                             " AND USERPOWER.POWERNAME = USERMENUPOWER.POWERNAME " +
                                             " AND USERMENUPOWER.MENUUSE = 'Y'" +
                                             " AND USERPOWER.POWERNAME = '{0}'", PowerName);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            List<string> menuNameList = new List<string>();
            while (sqlDataReader.Read())
            {
                if (this.LftSem.LanguageType.Equals("zh"))
                {
                    menuNameList.Add((string)sqlDataReader["CNNAME"]);
                }
                else
                {
                    menuNameList.Add((string)sqlDataReader["ENNAME"]);
                }
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            //获取页面tvMenuDisplay控件上的所有节点
            List<TreeNode> trees = new List<TreeNode>();
            foreach (TreeNode item in this.tvMenuUse.Nodes)
            {
                if (item.Nodes.Count > 0)
                {
                    foreach (TreeNode tree in item.Nodes)
                    {
                        trees.Add(tree);
                    }
                }
                trees.Add(item);
            }
            foreach (TreeNode parentNode in trees)
            {
                foreach (string name in menuNameList)
                {
                    if (name.Equals(parentNode.Text))
                    {
                        parentNode.Checked = true;
                    }
                }
            }
        }
        /// <summary>
        /// 添加菜单权限按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddMenuPower_Click(object sender, EventArgs e)
        {
            string menuPowerName = this.tbMenuPowerName.Text;
            string menuPower = this.tbMenuPower.Text;
            string menuNamePower = this.tbMenuNamePower.Text;
            string displayMenu = this.cbDisplayMenu.Text;
            string useMenu = this.cbUseMenu.Text;
            List<string> addDataList = new List<string>();
            if (menuPowerName.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            if (menuPower.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限不能为空", "Power cannot be empty");
                return;
            }
            if (menuNamePower.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单名不能为空", "The menu name cannot be empty");
                return;
            }
            if (displayMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("显示菜单选项不能为空", "Display menu options cannot be empty");
                return;
            }
            if (useMenu.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("使用菜单选项不能为空", "Use menu options cannot be empty");
                return;
            }
            addDataList.Add(menuPowerName);
            addDataList.Add(menuPower);
            addDataList.Add(menuNamePower);
            addDataList.Add(displayMenu);
            addDataList.Add(useMenu);
            //判断数据是否已经存在
            if (!CheckIsExist(menuPowerName, menuNamePower, true))
            {
                //数据不存在,则添加数据
                this.AddPowerMenu(addDataList);
                this.ClearPowerMenuInputDate();
            }
            else
            {
                //数据存在
                PopupNotice.DialogPopups("数据已经存在，请检查", "Data already exists, please check", enumPopupsType.Warning);
            }
        }
        private void AddPowerMenu(List<string> AddDataLists)
        {
            if (AddDataLists != null && AddDataLists.Count > 0)
            {
                try
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    string sqlString = string.Format("INSERT INTO USERMENUPOWER VALUES('{0}',{1},'{2}','{3}','{4}','{5}')", AddDataLists[0], Convert.ToInt32(AddDataLists[1]), AddDataLists[2], AddDataLists[3], AddDataLists[4], DateTime.Now);
                    int returnCode = dBConnection.ExecuteUpdate(sqlString);
                    if (returnCode > 0)
                    {
                        PopupNotice.DialogPopups("添加成功", "Add successfully", enumPopupsType.OK);
                    }
                    else
                    {
                        PopupNotice.DialogPopups("添加失败,请检查！！！", "Add failed, please check!!!", enumPopupsType.Error);
                    }
                    DBControl.RemoveDBConection(dBConnection);
                }
                catch (Exception ex)
                {
                    UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
                }
            }
        }
        /// <summary>
        /// 判断数据是否已经存在
        /// </summary>
        /// <returns></returns>
        private bool CheckIsExist(string powerName, string menuName, bool isNotModify)
        {
            bool Flag = false;
            if (!powerName.IsNullOrEmpty() && !menuName.IsNullOrEmpty())
            {
                string sqlString = "";
                //根据条件查询数据
                DBConnection dBConnection = DBControl.GetConnection();
                if (isNotModify)
                {
                    sqlString = string.Format("SELECT * FROM USERMENUPOWER WHERE POWERNAME = '{0}' AND MENUNAME = '{1}'", powerName, menuName);
                }
                else
                {
                    sqlString = string.Format("SELECT * FROM USERMENUPOWER WHERE POWERNAME = '{0}'", powerName);
                }
                SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
                if (sqlDataReader.Read())
                {
                    Flag = true;
                }
                if (sqlDataReader != null)
                {
                    sqlDataReader.Close();
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            return Flag;
        }
        /// <summary>
        /// 根据key查找所有数据
        /// </summary>
        private List<MenuPowerDao> GetDataByCase(MenuPowerDao menuPowerDao)
        {
            //根据条件查询数据
            List<MenuPowerDao> menuPowerDaos = new List<MenuPowerDao>();
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = string.Format("SELECT * FROM USERMENUPOWER WHERE POWERNAME = '{0}' AND MENUNAME = '{1}'", menuPowerDao.POWERNAME, menuPowerDao.MENUNAME);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            if (sqlDataReader.Read())
            {
                MenuPowerDao menuPower = new MenuPowerDao();
                menuPower.POWERNAME = (string)sqlDataReader["POWERNAME"];
                menuPower.POWER = (int)sqlDataReader["POWER"];
                menuPower.MENUNAME = (string)sqlDataReader["MENUNAME"];
                menuPower.MENUDISPLAY = (string)sqlDataReader["MENUDISPLAY"];
                menuPower.MENUUSE = (string)sqlDataReader["MENUUSE"];
                menuPowerDaos.Add(menuPower);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return menuPowerDaos;
        }
        /// <summary>
        /// 修改菜单权限按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btModifyMenuPower_Click(object sender, EventArgs e)
        {
            if (this.tbMenuPowerName.Text.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            if (this.tbMenuNamePower.Text.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单名不能为空", "The menu name cannot be empty");
                return;
            }
            string menuPowerName = this.tbMenuPowerName.Text;
            string menuNamePower = this.tbMenuNamePower.Text;
            MenuPowerDao menuPowerDao = new MenuPowerDao();
            menuPowerDao.POWERNAME = menuPowerName;
            menuPowerDao.MENUNAME = menuNamePower;
            //判断数据是否存在
            if (this.CheckIsExist(menuPowerName, menuNamePower, false))
            {

                if (tbMenuPower.Text.IsNullOrEmpty())
                {
                    menuPowerDao.POWER = this.GetDataByCase(menuPowerDao)[0].POWER;
                }
                else
                {
                    menuPowerDao.POWER = Convert.ToInt32(this.tbMenuPower.Text);
                }
                if (cbDisplayMenu.Text.IsNullOrEmpty())
                {
                    menuPowerDao.MENUDISPLAY = this.GetDataByCase(menuPowerDao)[0].MENUDISPLAY;
                }
                else
                {
                    menuPowerDao.MENUDISPLAY = cbDisplayMenu.Text;
                }
                if (cbUseMenu.Text.IsNullOrEmpty())
                {
                    menuPowerDao.MENUUSE = this.GetDataByCase(menuPowerDao)[0].MENUUSE;
                }
                else
                {
                    menuPowerDao.MENUUSE = cbUseMenu.Text;
                }
                //数据存在，则更新数据
                this.ModifyMenuPower(menuPowerDao);
                this.ClearPowerMenuInputDate();
            }
            else
            {
                //数据不存在，则弹窗警告
                PopupNotice.DialogPopups("数据不存在，请检查", "The data does not exist, please check", enumPopupsType.Warning);
            }
        }
        /// <summary>
        /// 修改菜单
        /// </summary>
        private void ModifyMenuPower(MenuPowerDao menuPowerDao)
        {
            if (menuPowerDao != null)
            {
                try
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    string sqlString = string.Format("UPDATE USERMENUPOWER SET POWER = '{0}',MENUNAME = '{1}',MENUDISPLAY = '{2}',MENUUSE = '{3}',MODIFYTIME = '{4}' WHERE POWERNAME = '{5}'", menuPowerDao.POWER, menuPowerDao.MENUNAME, menuPowerDao.MENUDISPLAY, menuPowerDao.MENUUSE, DateTime.Now, menuPowerDao.POWERNAME);
                    int returnCode = dBConnection.ExecuteUpdate(sqlString);
                    if (returnCode > 0)
                    {
                        PopupNotice.DialogPopups("修改成功", "Successfully modified", enumPopupsType.OK);
                    }
                    else
                    {
                        PopupNotice.DialogPopups("修改失败,请检查！！！", "Modification failed, please check!!!", enumPopupsType.Error);
                    }
                    DBControl.RemoveDBConection(dBConnection);
                }
                catch (Exception ex)
                {
                    UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
                }
            }
        }
        /// <summary>
        /// 删除菜单权限按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDeleteMenuPower_Click(object sender, EventArgs e)
        {
            string MenuPowerName = this.tbMenuPowerName.Text;
            string MenuNamePower = this.tbMenuNamePower.Text;
            if (MenuPowerName.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("权限名不能为空", "Power name cannot be empty");
                return;
            }
            if (MenuNamePower.IsNullOrEmpty())
            {
                PopupNotice.TipsPopups("菜单名不能为空", "The menu name cannot be empty");
                return;
            }
            if (this.CheckIsExist(MenuPowerName, MenuNamePower, true))
            {
                //数据存在，则删除数据
                MenuPowerDao menuPowerDao = new MenuPowerDao();
                menuPowerDao.POWERNAME = MenuPowerName;
                menuPowerDao.MENUNAME = MenuNamePower;
                this.DeleteMenuPower(menuPowerDao);
                this.ClearPowerMenuInputDate();
            }
            else
            {
                //数据不存在，则弹窗警告
                PopupNotice.DialogPopups("数据不存在，请检查", "The data does not exist, please check", enumPopupsType.Warning);
            }
        }
        /// <summary>
        /// 删除菜单权限
        /// </summary>
        private void DeleteMenuPower(MenuPowerDao menuPowerDao)
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("DELETE FROM USERMENUPOWER WHERE POWERNAME = '{0}' AND MENUNAME = '{1}'", menuPowerDao.POWERNAME, menuPowerDao.MENUNAME);
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                if (returnCode > 0)
                {
                    PopupNotice.DialogPopups("删除成功", "Successfully deleted", enumPopupsType.OK);
                }
                else
                {
                    PopupNotice.DialogPopups("删除失败,请检查！！！", "Delete failed, please check!!!", enumPopupsType.Error);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        /// <summary>
        /// 显示菜单下拉加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbDisplayMenu_DropDown(object sender, EventArgs e)
        {
            this.cbDisplayMenu.DataSource = new List<string>() { "", "Y", "N" };
        }
        /// <summary>
        /// 使用菜单下拉加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbUseMenu_DropDown(object sender, EventArgs e)
        {
            this.cbUseMenu.DataSource = new List<string>() { "", "Y", "N" };
        }

        private void ClearPowerMenuInputDate()
        {
            this.tbMenuPowerName.Text = "";
            this.tbMenuPower.Text = "";
            this.tbMenuNamePower.Text = "";
            this.cbDisplayMenu.Text = "";
            this.cbUseMenu.Text = "";
        }
        public class MenuPowerDao
        {
            public int ID { get; set; }
            public string POWERNAME { get; set; }
            public int POWER { get; set; }
            public string MENUNAME { get; set; }
            public string MENUDISPLAY { get; set; }
            public string MENUUSE { get; set; }
            public DateTime MODIFYTIME { get; set; }
        }
        private void tvMenuDisplay_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            bool test = e.Node.Checked;
            TreeNodeCollection Expanded = e.Node.Nodes;
        }

        private void InitTreeNode()
        {
            InitDisplayTreeNode();
            InitUseTreeNode();
        }
        private void InitDisplayTreeNode()
        {
            this.tvMenuDisplay.Nodes.Clear();
            //获取所有菜单权限
            Dictionary<MenuManageDao, List<MenuManageDao>> menus = this.GetMenuPowerDict();
            List<TreeNode> ParentDisplayTreeNodes = new List<TreeNode>();
            //初始化菜单节点
            foreach (KeyValuePair<MenuManageDao, List<MenuManageDao>> item in menus)
            {
                List<TreeNode> treeNodes = new List<TreeNode>();
                foreach (MenuManageDao childNode in item.Value)
                {
                    TreeNode treeNode;
                    if (this.LftSem.LanguageType.Equals("zh"))
                    {
                        treeNode = new TreeNode(childNode.CNNAME);
                    }
                    else
                    {
                        treeNode = new TreeNode(childNode.ENNAME);
                    }
                    treeNode.Name = childNode.ENNAME;
                    treeNodes.Add(treeNode);
                }
                TreeNode parentNode;
                if (this.LftSem.LanguageType.Equals("zh"))
                {
                    parentNode = new TreeNode(item.Key.CNNAME, treeNodes.ToArray());
                }
                else
                {
                    parentNode = new TreeNode(item.Key.ENNAME, treeNodes.ToArray());
                }
                parentNode.Name = item.Key.ENNAME;
                ParentDisplayTreeNodes.Add(parentNode);
            }
            this.tvMenuDisplay.Nodes.AddRange(ParentDisplayTreeNodes.ToArray());
            this.tvMenuDisplay.TreeNodeStateSync = false;
        }
        private void InitUseTreeNode()
        {
            this.tvMenuUse.Nodes.Clear();
            //获取所有菜单权限
            Dictionary<MenuManageDao, List<MenuManageDao>> menus = this.GetMenuPowerDict();
            List<TreeNode> ParentUseTreeNodes = new List<TreeNode>();
            //初始化菜单节点
            foreach (KeyValuePair<MenuManageDao, List<MenuManageDao>> item in menus)
            {
                List<TreeNode> treeNodes = new List<TreeNode>();
                foreach (MenuManageDao childNode in item.Value)
                {
                    TreeNode treeNode;
                    if (this.LftSem.LanguageType.Equals("zh"))
                    {
                        treeNode = new TreeNode(childNode.CNNAME);
                    }
                    else
                    {
                        treeNode = new TreeNode(childNode.ENNAME);
                    }
                    treeNode.Name = childNode.ENNAME;
                    treeNodes.Add(treeNode);
                }
                TreeNode parentNode;
                if (this.LftSem.LanguageType.Equals("zh"))
                {
                    parentNode = new TreeNode(item.Key.CNNAME, treeNodes.ToArray());
                }
                else
                {
                    parentNode = new TreeNode(item.Key.ENNAME, treeNodes.ToArray());
                }
                parentNode.Name = item.Key.ENNAME;
                ParentUseTreeNodes.Add(parentNode);
            }
            this.tvMenuUse.Nodes.AddRange(ParentUseTreeNodes.ToArray());
            this.tvMenuUse.TreeNodeStateSync = false;
        }
        /// <summary>
        /// 获取所有的权限菜单数据，返回一个字典对象
        /// </summary>
        /// <returns></returns>
        private Dictionary<MenuManageDao, List<MenuManageDao>> GetMenuPowerDict()
        {
            List<MenuManageDao> ParentMenu = new List<MenuManageDao>();
            Dictionary<MenuManageDao, List<MenuManageDao>> menuDict = new Dictionary<MenuManageDao, List<MenuManageDao>>();
            DBConnection dBConnection = DBControl.GetConnection();
            //获取父级菜单
            string sqlString = string.Format("SELECT USERMENU.ID,USERMENU.CNNAME,USERMENU.ENNAME"
                                           + " FROM USERMENU"
                                           + " WHERE USERMENU.PARENTID = '-1'");
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                MenuManageDao menuManageDao = new MenuManageDao();
                menuManageDao.ID = (int)sqlDataReader["ID"];
                menuManageDao.CNNAME = (string)sqlDataReader["CNNAME"];
                menuManageDao.ENNAME = (string)sqlDataReader["ENNAME"];
                ParentMenu.Add(menuManageDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            //获取每个父级菜单下面的子级菜单
            if (ParentMenu != null && ParentMenu.Count > 0)
            {
                foreach (MenuManageDao item in ParentMenu)
                {
                    List<MenuManageDao> MenuLists = new List<MenuManageDao>();
                    string sqlStringParent = string.Format("SELECT * FROM USERMENU WHERE PARENTID = {0}", item.ID);
                    SqlDataReader sqlDataReader1 = dBConnection.ExecuteQuery(sqlStringParent);
                    while (sqlDataReader1.Read())
                    {
                        MenuManageDao menuManageDao = new MenuManageDao();
                        menuManageDao.CNNAME = (string)sqlDataReader1["CNNAME"];
                        menuManageDao.ENNAME = (string)sqlDataReader1["ENNAME"];
                        MenuLists.Add(menuManageDao);
                    }
                    menuDict.Add(item, MenuLists);
                }
            }
            return menuDict;
        }
        /// <summary>
        /// 保存菜单权限配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveMenuDisplayData();
                SaveMenuUseData();
                PopupNotice.DialogPopups("保存成功", "Successfully saved ", enumPopupsType.OK);
                this.ClearPowerMenuInputDate();
            }
            catch (Exception ex)
            {
                UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.ErrorTitle, showCancelButton: false, UIStyle.Red, false, false);
            }
        }
        private void SaveMenuDisplayData()
        {
            string PowerName = DGVUserPower.Rows[this.DGVUserPower.SelectedIndex].Cells[1].Value.ToString();
            if (PowerName.IsNullOrEmpty())
            {
                return;
            }
            List<UpdateNode> displayUpdateNodes = new List<UpdateNode>();
            //获取所有显示菜单节点
            foreach (TreeNode node in this.tvMenuDisplay.Nodes)
            {
                UpdateNode updateNode = new UpdateNode();
                updateNode.PowerName = PowerName;
                updateNode.MenuName = node.Name;
                if (node.Checked)
                {
                    updateNode.MenuDisplay = "Y";
                }
                else
                {
                    updateNode.MenuDisplay = "N";
                }
                displayUpdateNodes.Add(updateNode);
                if (node.Nodes.Count > 0)
                {
                    foreach (TreeNode childNode in node.Nodes)
                    {
                        UpdateNode childUpdateNode = new UpdateNode();
                        childUpdateNode.PowerName = PowerName;
                        childUpdateNode.MenuName = childNode.Name;
                        if (childNode.Checked)
                        {
                            childUpdateNode.MenuDisplay = "Y";
                        }
                        else
                        {
                            childUpdateNode.MenuDisplay = "N";
                        }
                        displayUpdateNodes.Add(childUpdateNode);
                    }
                }
            }

            //更新数据库
            DBConnection dBConnection = DBControl.GetConnection();
            try
            {
                foreach (UpdateNode displayNode in displayUpdateNodes)
                {
                    string sqlString = string.Format("UPDATE USERMENUPOWER SET MENUDISPLAY = '{0}',MODIFYTIME = '{3}' WHERE POWERNAME = '{1}' AND MENUNAME = '{2}'", displayNode.MenuDisplay, displayNode.PowerName, displayNode.MenuName, DateTime.Now);
                    dBConnection.ExecuteQuery(sqlString);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                DBControl.RemoveDBConection(dBConnection);
            }
        }
        private void SaveMenuUseData()
        {
            string PowerName = DGVUserPower.Rows[this.DGVUserPower.SelectedIndex].Cells[1].Value.ToString();
            if (PowerName.IsNullOrEmpty())
            {
                return;
            }
            List<UpdateNode> MenuUseUpdateNodes = new List<UpdateNode>();
            //获取所有显示菜单节点
            foreach (TreeNode node in this.tvMenuUse.Nodes)
            {
                UpdateNode updateNode = new UpdateNode();
                updateNode.PowerName = PowerName;
                updateNode.MenuName = node.Name;
                if (node.Checked)
                {
                    updateNode.MenuUse = "Y";
                }
                else
                {
                    updateNode.MenuUse = "N";
                }
                MenuUseUpdateNodes.Add(updateNode);
                if (node.Nodes.Count > 0)
                {
                    foreach (TreeNode childNode in node.Nodes)
                    {
                        UpdateNode childUpdateNode = new UpdateNode();
                        childUpdateNode.PowerName = PowerName;
                        childUpdateNode.MenuName = childNode.Name;
                        if (childNode.Checked)
                        {
                            childUpdateNode.MenuUse = "Y";
                        }
                        else
                        {
                            childUpdateNode.MenuUse = "N";
                        }
                        MenuUseUpdateNodes.Add(childUpdateNode);
                    }
                }
            }

            //更新数据库
            DBConnection dBConnection = DBControl.GetConnection();
            try
            {
                foreach (UpdateNode displayNode in MenuUseUpdateNodes)
                {
                    string sqlString = string.Format("UPDATE USERMENUPOWER SET MENUUSE = '{0}', MODIFYTIME = '{3}' WHERE POWERNAME = '{1}' AND MENUNAME = '{2}'", displayNode.MenuUse, displayNode.PowerName, displayNode.MenuName, DateTime.Now);
                    dBConnection.ExecuteQuery(sqlString);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                DBControl.RemoveDBConection(dBConnection);
            }
        }
        private class UpdateNode
        {
            public string PowerName { get; set; }
            public string MenuName { get; set; }
            public string MenuDisplay { get; set; }
            public string MenuUse { get; set; }
        }
        #endregion
        private void cbParentMenu_TextChanged(object sender, EventArgs e)
        {
            string ParentMenu = this.cbParentMenu.Text;
            if (!ParentMenu.IsNullOrEmpty())
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string sqlString = string.Format("SELECT ID FROM USERMENU WHERE ENNAME = '{0}'", ParentMenu);
                SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
                while (sqlDataReader.Read())
                {
                    this.tbParentID.Text = sqlDataReader["ID"].ToString();
                }
            }
            else
            {
                this.tbParentID.Text = "";
            }
        }
        #region Port配置功能
        /// <summary>
        /// 查询Port信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSearchPortInfo_Click(object sender, EventArgs e)
        {
            SearchPortConfigInfo(false);
        }
        /// <summary>
        /// 查询Port配置信息
        /// </summary>
        /// <param name="RefreshFlag">是否为刷新操作，true:刷新操作；false:查询操作</param>
        private void SearchPortConfigInfo(bool RefreshFlag)
        {
            string inputPortID = this.tbInputTxt.Text;
            if (RefreshFlag)
            {
                inputPortID = "";
            }

            //显示到界面
            this.PortInfoDGV.DataSource = this.SearchLifterPortInfo(inputPortID);
            this.LocationUnitInfoDGV.DataSource = this.SearchLocUnitInfo(inputPortID);
            this.SubSystemInfoDGV.DataSource = this.SearchSubSystemInfo(inputPortID);
        }

        /// <summary>
        ///查询Port表信息
        /// </summary>
        private List<LifterPortDao> SearchLifterPortInfo(string PortID)
        {
            List<LifterPortDao> lifterPorts = new List<LifterPortDao>();
            string sqlString = "SELECT * FROM LIFTERPORT";
            //如果PortID不为空，则按PortID查询数据信息
            if (!string.IsNullOrEmpty(PortID))
            {
                sqlString = string.Format("SELECT * FROM LIFTERPORT WHERE ID = '{0}'", PortID);
            }

            DBConnection dBConnection = DBControl.GetConnection();

            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                LifterPortDao lifterPort = new LifterPortDao();
                lifterPort.LifterID = (string)sqlDataReader["ID"];
                lifterPort.HandOffType = (string)sqlDataReader["HANDOFFTYPE"];
                lifterPort.PortType = (string)sqlDataReader["PORTTYPE"];
                lifterPort.PortSize = (int)sqlDataReader["PORTSIZE"];
                lifterPort.ElevType = (string)sqlDataReader["ELEVTYPE"];
                lifterPort.IsCombine = (string)sqlDataReader["ISCOMBINE"];
                lifterPort.IsNextLoc = (string)sqlDataReader["ISNEXTLOC"];
                lifterPort.Floor = (int)sqlDataReader["FLOOR"];
                lifterPorts.Add(lifterPort);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return lifterPorts;
        }
        /// <summary>
        /// 查询Unit表信息
        /// </summary>
        private List<LocationUnitDao> SearchLocUnitInfo(string PortID)
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetLifter();
            List<LocationUnitDao> locationUnitDaos = new List<LocationUnitDao>();
            string sqlString = "SELECT * FROM LOCATIONUNIT";
            //如果PortID不为空，则按PortID查询数据信息
            if (!string.IsNullOrEmpty(PortID))
            {
                sqlString = string.Format("SELECT * FROM LOCATIONUNIT WHERE ID = '{0}'", PortID);
            }

            DBConnection dBConnection = DBControl.GetConnection();

            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                LocationUnitDao locationUnitDao = new LocationUnitDao();
                locationUnitDao.Id = (string)sqlDataReader["ID"];
                locationUnitDao.PlcID = (string)sqlDataReader["PLCID"];
                locationUnitDao.HostID = lifterSEM.HostID + (string)sqlDataReader["HOSTID"];
                locationUnitDaos.Add(locationUnitDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return locationUnitDaos;
        }
        /// <summary>
        /// 查询子系统表信息
        /// </summary>
        private List<SubSystemDao> SearchSubSystemInfo(string PortID)
        {
            List<SubSystemDao> subSystemDaos = new List<SubSystemDao>();
            string sqlString = "SELECT * FROM SUBSYSTEM";
            //如果PortID不为空，则按PortID查询数据信息
            if (!string.IsNullOrEmpty(PortID))
            {
                sqlString = string.Format("SELECT * FROM SUBSYSTEM WHERE SUBSYSTEMID = '{0}'", PortID);
            }

            DBConnection dBConnection = DBControl.GetConnection();

            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                SubSystemDao subSystem = new SubSystemDao();
                subSystem.SubSystemID = (string)sqlDataReader["SUBSYSTEMID"];
                subSystem.SubSystemType = (string)sqlDataReader["SUBSYSTEMTYPE"];
                subSystem.OwnerID = (string)sqlDataReader["OWNERID"];
                subSystem.OwnerType = (string)sqlDataReader["OWNERTYPE"];
                subSystem.AssemblyName = (string)sqlDataReader["ASSEMBLYNAME"];
                subSystem.ClassName = (string)sqlDataReader["CLASSNAME"];
                subSystemDaos.Add(subSystem);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return subSystemDaos;
        }
        /// <summary>
        /// 添加Port配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddPortInfo_Click(object sender, EventArgs e)
        {
            if (!CheckInputIsEmpty())
            {
                return;
            }
            AddPortConfigInfo();
            SearchPortConfigInfo(true);
        }
        /// <summary>
        /// 添加Port配置信息
        /// </summary>
        private void AddPortConfigInfo()
        {
            string portID = this.tbPortTbPortID.Text;
            //判断数据是否存在
            if (this.SearchLifterPortInfo(portID).Count > 0 && this.SearchLocUnitInfo(portID).Count > 0 && this.SearchSubSystemInfo(portID).Count > 0)
            {
                PopupNotice.DialogPopups("当前PortID数据已存在，请检查！！！", "The current PortID data already exists, please check!!!", enumPopupsType.Warning);
                return;
            }
            else
            {
                try
                {
                    //执行添加Port配置信息操作
                    DBConnection dBConnection = DBControl.GetConnection();

                    //获取LifterPort界面输入数据
                    string portTbPortID = this.tbPortTbPortID.Text;
                    string handOffType = this.tbHandOffType.Text;
                    string portType = this.tbPortType.Text;
                    int bufferSize = Convert.ToInt32(this.tbBufferSize.Text);
                    string type = this.tbType.Text;
                    string isCombine = this.tbIsCombine.Text;
                    string nextLoc = this.tbNextLoc.Text;
                    string exceptionFloor = this.tbExceptionFloor.Text;

                    //获取LocationUnit界面输入数据
                    string unitTbPortID = this.tbUnitTbPortID.Text;
                    string plcID = this.tbPLCID.Text;
                    string hostID = this.tbHostID.Text;

                    //获取subsystem界面输入数据
                    string subsystemID = this.tbSubsystemID.Text;
                    string subsystemType = this.tbSubsystemType.Text;
                    string ownerID = this.tbOwnerID.Text;
                    string ownerType = this.tbOwnerType.Text;
                    string assemblyName = this.tbAssemblyName.Text;
                    string className = this.tbClassName.Text;

                    string portSqlString = string.Format("INSERT INTO LIFTERPORT VALUES('{0}','{1}','{2}',{3},'{4}','{5}','{6}','{7}')", portTbPortID, handOffType, portType, bufferSize, type, isCombine, nextLoc, exceptionFloor);//LifterPort表添加语句
                    string unitSqlString = string.Format("INSERT INTO LOCATIONUNIT VALUES('{0}','{1}','{2}')", unitTbPortID, plcID, hostID); //LocationUnit表添加语句
                    string systemSqlString = string.Format("INSERT INTO SUBSYSTEM VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", subsystemID, subsystemType, ownerID, ownerType, assemblyName, className); //SubSystem表添加语句

                    int portReturnCode = dBConnection.ExecuteUpdate(portSqlString);
                    int unitReturnCode = dBConnection.ExecuteUpdate(unitSqlString);
                    int systemReturnCode = dBConnection.ExecuteUpdate(systemSqlString);

                    if (portReturnCode > 0 && unitReturnCode > 0 && systemReturnCode > 0)
                    {
                        PopupNotice.DialogPopups("添加成功", "Added successfully", enumPopupsType.OK);
                    }
                    else
                    {
                        PopupNotice.DialogPopups("添加失败，请检查！！！", "Add failed, please check!!!", enumPopupsType.Error);
                    }
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups("添加失败:" + ex.Message, ex.Message, enumPopupsType.Error);
                }
            }
        }
        /// <summary>
        /// 检查输入的数据是否为空
        /// </summary>
        private bool CheckInputIsEmpty()
        {
            if (string.IsNullOrEmpty(this.tbPortTbPortID.Text))
            {
                PopupNotice.TipsPopups("PortTb的PortID输入信息为空", "The PortID input information of PortTb is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbType.Text))
            {
                PopupNotice.TipsPopups("Port类型输入信息为空", "Port type input information is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbHandOffType.Text))
            {
                PopupNotice.TipsPopups("Port传输类型输入信息为空", "Port HandOffType input information is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbBufferSize.Text))
            {
                PopupNotice.TipsPopups("Port的buffer size输入信息为空", "The input information for the buffer size of Port is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbHostID.Text))
            {
                PopupNotice.TipsPopups("HostID输入信息为空", "HostID input information is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbPLCID.Text))
            {
                PopupNotice.TipsPopups("PLCID输入信息为空", "PLCID input information is empty");
                return false;
            }
            if (string.IsNullOrEmpty(this.tbSubsystemID.Text))
            {
                PopupNotice.TipsPopups("单元ID输入为空", "Unit ID input is empty");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 删除port配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDeletePortInfo_Click(object sender, EventArgs e)
        {
            string portID = this.tbInputTxt.Text;
            DeletePortConfigInfo(portID);
            SearchPortConfigInfo(true);
        }
        private void DeletePortConfigInfo(string portID)
        {
            if (string.IsNullOrEmpty(portID))
            {
                PopupNotice.DialogPopups("请输入需要删除的PortID", "Please enter the PortID that needs to be deleted", enumPopupsType.Warning);
            }
            else
            {
                //判断当前PortID数据是否存在
                if (this.SearchLifterPortInfo(portID).Count > 0 && this.SearchLocUnitInfo(portID).Count > 0 && this.SearchSubSystemInfo(portID).Count > 0)
                {
                    try
                    {
                        //执行删除操作
                        DBConnection dBConnection = DBControl.GetConnection();
                        string lftSqlString = string.Format("DELETE FROM LIFTERPORT WHERE ID = '{0}'", portID);
                        string locunitSqlString = string.Format("DELETE FROM LOCATIONUNIT WHERE ID = '{0}'", portID);
                        string subsystemSqlString = string.Format("DELETE FROM SUBSYSTEM WHERE SUBSYSTEMID = '{0}'", portID);
                        int lftReturnCode = dBConnection.ExecuteUpdate(lftSqlString);
                        int unitReturnCode = dBConnection.ExecuteUpdate(locunitSqlString);
                        int systemReturnCode = dBConnection.ExecuteUpdate(subsystemSqlString);
                        if (lftReturnCode > 0 && unitReturnCode > 0 && systemReturnCode > 0)
                        {
                            PopupNotice.DialogPopups("删除成功", "Delete failed, please check", enumPopupsType.OK);
                        }
                        else
                        {
                            PopupNotice.DialogPopups("删除失败,请检查！！", "Delete failed, please check", enumPopupsType.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        PopupNotice.DialogPopups("删除失败:" + ex.Message, ex.Message, enumPopupsType.Error);
                    }
                }
                else
                {
                    PopupNotice.DialogPopups("删除失败，输入的PortID信息数据在表里不存在", "Delete failed, the input PortID information data does not exist", enumPopupsType.Error);
                }
            }
        }
        /// <summary>
        /// 当PortID输入值改变时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbPortTbPortID_TextChanged(object sender, EventArgs e)
        {
            this.tbUnitTbPortID.Text = this.tbPortTbPortID.Text;
            this.tbSubsystemID.Text = this.tbPortTbPortID.Text;
        }

        private void tbInputTxt_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.SearchPortConfigInfo(false);
            }
        }

        private void UITBConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.AlarmStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            this.AlarmEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 导入数据库Observable文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Importobservable_Click(object sender, EventArgs e)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            string sql = "delete from OBSERVABLE;";
            dBConnection.ExecuteUpdate(sql);
            dBConnection.Close();
            FileStream fs = null;
            //IWorkbook相当于整个excel文件
            IWorkbook workbook = null;//IWorkbook是一个接口，XSSFWorkbook和HSSFWorkbook都继承自此接口
            DataTable dt = new DataTable();
            try
            {
                string file = null;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = true;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件夹";
                dialog.Filter = "所有文件(*.*)|*.xls";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    file = dialog.FileName;
                }
                if (file != null)
                {
                    string fileName = string.Format(file);//C:\Users\T3800\Desktop\1.xls  D:\Users\Sunmerx\Desktop\1.xls
                                                          //【1】读取excel文件，并新建workbook和sheet
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    if (fileName.IndexOf(".xlsx") > 0)      // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else if (fileName.IndexOf(".xls") > 0)  // 97-2003版本
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                }
                else
                {
                    return;
                }
                //ISheet相当于excel一个sheet
                ISheet sheet = workbook.GetSheetAt(0);    //读取第一个sheet


                dt.TableName = sheet.SheetName;

                //解析sheet的第一行数据，添加dt的列头名
                int startRow = 0;   //开始读取行数 
                IRow firstRow = sheet.GetRow(startRow);   //第一行 
                int cellCount = firstRow.LastCellNum;     //一行最后一个cell的编号,即总的列数
                AccessType accessType = AccessType.IN;
                ElementType elementType = ElementType.EQUIPMENT;
                DataType dataType = DataType.BOOLEAN;
                bool isMonitoring = false;

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null) continue; //没有数据的行默认是null
                    if (row != null)
                    {
                        if (row.GetCell(0) != null)
                        {
                            this.tbelementId.Text = row.GetCell(1).ToString();
                            this.tbelementType.Text = row.GetCell(2).ToString();
                            this.tbobservableId.Text = row.GetCell(3).ToString();
                            this.tbobservablePath.Text = row.GetCell(4).ToString();
                            this.tbaccessType.Text = row.GetCell(5).ToString();
                            this.tbdataType.Text = row.GetCell(6).ToString();
                            this.tbmin.Text = row.GetCell(7).ToString();
                            this.tbmax.Text = row.GetCell(8).ToString();
                            this.tbisMonitoring.Text = row.GetCell(10).ToString();
                            string connectionInfoString = row.GetCell(11).ToString();
                            this.tbdescription.Text = row.GetCell(12).ToString();
                            switch (this.tbelementType.Text)
                            {
                                case "Equipment":
                                    elementType = ElementType.EQUIPMENT;
                                    break;
                                case "SubSystem":
                                    elementType = ElementType.SUBSYSTEM;
                                    break;
                                case "Module":
                                    elementType = ElementType.MODULE;
                                    break;
                            }
                            switch (this.tbaccessType.Text)
                            {
                                case "In":
                                    accessType = AccessType.IN;
                                    break;
                                case "Out":
                                    accessType = AccessType.OUT;
                                    break;
                                case "In_Out":
                                    accessType = AccessType.IN_OUT;
                                    break;
                            }
                            switch (this.tbdataType.Text)
                            {
                                case "Boolean":
                                    dataType = DataType.BOOLEAN;
                                    break;
                                case "Byte":
                                    dataType = DataType.BYTE;
                                    break;
                                case "Short":
                                    dataType = DataType.SHORT;
                                    break;
                                case "String":
                                    dataType = DataType.STRING;
                                    break;
                            }
                            switch (this.tbisMonitoring.Text)
                            {
                                case "T":
                                    isMonitoring = true;
                                    break;
                                case "F":
                                    isMonitoring = false;
                                    break;
                            }
                            try
                            {
                                Observable value = Observable.CreateObservable(this.tbelementId.Text, elementType, this.tbobservableId.Text, this.tbobservablePath.Text, accessType, dataType, Convert.ToDouble(this.tbmin.Text), Convert.ToDouble(this.tbmax.Text), 1, isMonitoring, connectionInfoString, this.tbdescription.Text, true, "..", "lifter");
                            }
                            catch (Exception ex)
                            {
                                PopupNotice.DialogPopups("点位添加失败", "Failed added point", enumPopupsType.Error);
                                throw ex;
                            }
                        }

                    }
                }
                //使用完excel文件后，一定要关闭
                PopupNotice.DialogPopups("点位添加成功", "Successfully added point", enumPopupsType.OK);
                fs.Close();
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 警报导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAlarmImportLog_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            //IWorkbook相当于整个excel文件
            IWorkbook workbook = null;//IWorkbook是一个接口，XSSFWorkbook和HSSFWorkbook都继承自此接口
            DataTable dt = new DataTable();
            try
            {
                string file = null;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = true;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件夹";
                dialog.Filter = "所有文件(*.*)|*.xls";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    file = dialog.FileName;
                }
                if (file != null)
                {
                    string fileName = string.Format(file);
                    //【1】读取excel文件，并新建workbook和sheet
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    if (fileName.IndexOf(".xlsx") > 0)      // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else if (fileName.IndexOf(".xls") > 0)  // 97-2003版本
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                }
                else
                {
                    return;
                }
                //ISheet相当于excel一个sheet
                ISheet sheet = workbook.GetSheetAt(0);    //读取第一个sheet
                dt.TableName = sheet.SheetName;
                //解析sheet的第一行数据，添加dt的列头名
                int startRow = 0;   //开始读取行数 
                IRow firstRow = sheet.GetRow(startRow);   //第一行 
                int cellCount = firstRow.LastCellNum;     //一行最后一个cell的编号,即总的列数
                AccessType accessType = AccessType.IN;
                ElementType elementType = ElementType.EQUIPMENT;
                DataType dataType = DataType.BOOLEAN;
                try
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    string sql = "delete from ALARM;";
                    dBConnection.ExecuteUpdate(sql);
                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null
                        if (row != null)
                        {
                            if (row.GetCell(0) != null)
                            {
                                this.tbAddAlarmID.Text = row.GetCell(0).ToString();
                                this.tbAddAlarmCode.Text = row.GetCell(1).ToString();
                                this.tbAddAlarmText.Text = row.GetCell(2).ToString();
                                this.cbAddAlarmType.Text = row.GetCell(3).ToString();
                                this.cbAddAlarmUse.Text = row.GetCell(4).ToString();
                                this.tbAddAlarmCause.Text = row.GetCell(5).ToString();
                                this.tbAlarmSolution.Text = row.GetCell(6).ToString();
                                string createTime = Util.GetNowDateTimeString(dateTimeFormat.yyyy_MM_ddHHmmss);
                                //获取页面输入框数据，并存入字典里面
                                Dictionary<string, string> AlarmDict = new Dictionary<string, string>();
                                AlarmDict.Add("ALID", this.tbAddAlarmID.Text);
                                AlarmDict.Add("ALCD", this.tbAddAlarmCode.Text);
                                AlarmDict.Add("ALTX", this.tbAddAlarmText.Text);
                                AlarmDict.Add("SUBSYSTEM", this.cbAddAlarmType.Text);
                                AlarmDict.Add("IS_HOST_REPORT", this.cbAddAlarmUse.Text);
                                AlarmDict.Add("CREATETIME", createTime);
                                AlarmDict.Add("CAUSE", this.tbAddAlarmCause.Text);
                                AlarmDict.Add("SOLUTION", this.tbAlarmSolution.Text);
                                //创建alarm
                                this.lifterAlarm.AddAllAlarm(AlarmDict, dBConnection);
                            }
                        }
                    }
                    dBConnection.Close();
                    InitShowAlarms();
                    PopupNotice.DialogPopups("创建成功", "Created successfully", enumPopupsType.OK);
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups("创建报警失败", "Failed to create alarm", enumPopupsType.Error);
                    throw ex;
                }
                //使用完excel文件后，一定要关闭
                fs.Close();
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 警报文件导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAlarmExportLog_Click(object sender, EventArgs e)
        {
            if (this.AlarmDataGridView.Rows.Count <= 0)
            {
                UIMessageDialog.ShowMessageDialog("请先查询历史记录", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
            }
            else
            {
                new Thread(new ThreadStart(this.SaveToCVS)).Start();
            }
        }
        private void SaveToCVS()
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            string fileName = null;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择一个目录作为路径：";
            dialog.ShowNewFolderButton = true;
            dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            DialogResult result = DialogResult.OK;
            Thread t = new Thread((ThreadStart)(() =>
            {
                result = dialog.ShowDialog();
            }
));
            string userDefinedPropertyValue = null;
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
            if (result == DialogResult.OK)
            {
                t.Abort();
                userDefinedPropertyValue = string.Format(dialog.SelectedPath);
                fileName = userDefinedPropertyValue + "TRS_" + DateTime.Now.ToString("yyyy-MM-dd HHmmssfff") + ".xls";
            }
            else
            {
                userDefinedPropertyValue = this.LftSem.GetUserDefinedPropertyValue("ALARMEXPORTPATH", "./Alarm", true);
                fileName = userDefinedPropertyValue +"TRS_" + DateTime.Now.ToString("yyyy-MM-dd HHmmssfff") + ".xls";
                if (!Directory.Exists(userDefinedPropertyValue))
                {
                    Directory.CreateDirectory(userDefinedPropertyValue);
                }
            }
            try
            {
                using (StreamWriter streamWriter = new StreamWriter(new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)))
                {
                    streamWriter.WriteLine("警报ID" + "\t" + "警报代码" + "\t" + "报警内容" + "\t" + "报警类型" + "\t" + "是否启用" + "\t" + "报警原因" + "\t" + "解决方案" + "\t" + "创建时间");//设置表头
                    StringBuilder stringBuilder = new StringBuilder();
                    //AllRows.Count
                    foreach (AlarmDao Transfer in this.AlarmsList)
                    {
                        string row = "";
                        row = row + Transfer.ALCD + '\t' + Transfer.ALID + '\t' + Transfer.ALTX + '\t' + Transfer.SUBSYSTEM + '\t' + Transfer.IS_HOST_REPORT + '\t'  + Transfer.CAUSE + '\t' + Transfer.SOLUTION + '\t' + Transfer.CREATETIME + '\t';
                        streamWriter.WriteLine(row.Trim());
                        Thread.Sleep(0);
                    }
                    AcrossThreads();
                }
            }
            catch (Exception)
            {
                PopupNotice.DialogPopups("无法保存为文件!!", "Unable to save as file!!", enumPopupsType.Error);
            }
            finally
            {
                PopupNotice.DialogPopups("[" + fileName + "]文件创建完成.", "[" + fileName + "]File creation completed", enumPopupsType.OK);
            }
        }
        private void AcrossThreads()
        {
            var MethInvo = new MethodInvoker(UpdataDgv);
            this.BeginInvoke(MethInvo);
        }
        void UpdataDgv()
        {
            //初始化获取所有的Alarm
            LifterAlarm lifterAlarm = LifterAlarm.GetLifterAlarm();
            AlarmsList = lifterAlarm.GetAllAlarm(null);
            this.InitDataGridView(AlarmsList);
            //初始化下拉框数据
            this.AlarmTypeList.Add("");
            this.AlarmTypeList.AddRange(Util.ObjectListToStringList(AlarmsList, "SUBSYSTEM").Distinct().ToList<string>());
            this.AlarmUseList.Add("");
            this.AlarmUseList.AddRange(Util.ObjectListToStringList(AlarmsList, "IS_HOST_REPORT").Distinct().ToList<string>());
            this.cbAddAlarmType.DataSource = AlarmTypeList;
            this.cbAddAlarmUse.DataSource = AlarmUseList;
        }

        private void btBulkImport_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            //IWorkbook相当于整个excel文件
            IWorkbook workbook = null;//IWorkbook是一个接口，XSSFWorkbook和HSSFWorkbook都继承自此接口
            DataTable dt = new DataTable();
            try
            {
                string file = null;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = true;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件夹";
                dialog.Filter = "所有文件(*.*)|*.xls";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    file = dialog.FileName;
                }
                if (file != null)
                {
                    string fileName = string.Format(file);
                    //【1】读取excel文件，并新建workbook和sheet
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    if (fileName.IndexOf(".xlsx") > 0)      // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else if (fileName.IndexOf(".xls") > 0)  // 97-2003版本
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                }
                else
                {
                    return;
                }
                //ISheet相当于excel一个sheet
                ISheet sheet = workbook.GetSheetAt(0);    //读取第一个sheet
                dt.TableName = sheet.SheetName;
                //解析sheet的第一行数据，添加dt的列头名
                int startRow = 0;   //开始读取行数 
                IRow firstRow = sheet.GetRow(startRow);   //第一行 
                int cellCount = firstRow.LastCellNum;     //一行最后一个cell的编号,即总的列数
                AccessType accessType = AccessType.IN;
                ElementType elementType = ElementType.EQUIPMENT;
                DataType dataType = DataType.BOOLEAN;
                try
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null
                        if (row != null)
                        {
                            if (row.GetCell(0) != null)
                            {
                                this.tbAddAlarmID.Text = row.GetCell(0).ToString();
                                this.tbAddAlarmCode.Text = row.GetCell(1).ToString();
                                this.tbAddAlarmText.Text = row.GetCell(2).ToString();
                                this.cbAddAlarmType.Text = row.GetCell(3).ToString();
                                this.cbAddAlarmUse.Text = row.GetCell(4).ToString();
                                this.tbAddAlarmCause.Text = row.GetCell(5).ToString();
                                this.tbAlarmSolution.Text = row.GetCell(6).ToString();
                                string createTime = Util.GetNowDateTimeString(dateTimeFormat.yyyy_MM_ddHHmmss);
                                //获取页面输入框数据，并存入字典里面
                                Dictionary<string, string> AlarmDict = new Dictionary<string, string>();
                                AlarmDict.Add("ALID", this.tbAddAlarmID.Text);
                                AlarmDict.Add("ALCD", this.tbAddAlarmCode.Text);
                                AlarmDict.Add("ALTX", this.tbAddAlarmText.Text);
                                AlarmDict.Add("SUBSYSTEM", this.cbAddAlarmType.Text);
                                AlarmDict.Add("IS_HOST_REPORT", this.cbAddAlarmUse.Text);
                                AlarmDict.Add("CREATETIME", createTime);
                                AlarmDict.Add("CAUSE", this.tbAddAlarmCause.Text);
                                AlarmDict.Add("SOLUTION", this.tbAlarmSolution.Text);
                                //创建alarm
                                this.lifterAlarm.AddBulkAlarm(AlarmDict);
                            }
                        }
                    }
                    dBConnection.Close();
                    InitShowAlarms();
                    PopupNotice.DialogPopups("创建成功", "Created successfully", enumPopupsType.OK);
                }
                catch (Exception ex)
                {
                    PopupNotice.DialogPopups("创建报警失败", "Failed to create alarm", enumPopupsType.Error);
                    throw ex;
                }
                //使用完excel文件后，一定要关闭
                fs.Close();
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                throw new Exception(ex.Message);
            }
        }

        private void btSystemOn_Click(object sender, EventArgs e)
        {
            this.LftSem.SecsDriver.SendMessage("S6F11", "501", this.LftSem);
            this.LftSem.SecsDriver.SendMessage("S6F11", "403", this.LftSem.ShuttleMaster);
        }

        private void btSystemOff_Click(object sender, EventArgs e)
        {
            this.LftSem.SecsDriver.SendMessage("S6F11", "502", this.LftSem);
            this.LftSem.SecsDriver.SendMessage("S6F11", "404", this.LftSem.ShuttleMaster);
        }

        private void btUpdateEqpInfoConfig_Click(object sender, EventArgs e)
        {
            if (!LftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.LftSem.UserPrivilige)
                {
                    this.LftSem.LoginTimeCount = 1;
                }
                ModifyEqpConfigInfo modifyEqpConfigInfo = new ModifyEqpConfigInfo();
                modifyEqpConfigInfo.ShowDialog();
                if (modifyEqpConfigInfo.IsOK)
                {
                   modifyEqpConfigInfo.UpdateEQPInfo();
                    this.LoadAllEqpInfoConfig();
                }
                modifyEqpConfigInfo.Dispose();
            }
        }

        private void btUpdateUnitInfoConfig_Click(object sender, EventArgs e)
        {
            if (!LftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.LftSem.UserPrivilige)
                {
                    this.LftSem.LoginTimeCount = 1;
                }
                ModifyUnitConfigInfo modifyUnitConfigInfo = new ModifyUnitConfigInfo();
                modifyUnitConfigInfo.ShowDialog();
                if (modifyUnitConfigInfo.IsOK)
                {
                    modifyUnitConfigInfo.UpdateUnitInfo();
                    this.LoadAllUnitInfoConfig();
                }
                modifyUnitConfigInfo.Dispose();
            }
        }

        private void btDeleteEqpInfoConfig_Click(object sender, EventArgs e)
        {
            if (!LftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.LftSem.UserPrivilige)
                {
                    this.LftSem.LoginTimeCount = 1;
                }
                
                if (UIMessageDialog.ShowAskDialog(this.ParentForm,$"确认要删除参数名为{this.eqpInfoConfigDgvSelectName}配置信息"))
                {
                    //删除EQP配置信息
                    this.DeleteEqpInfo();
                    this.LoadAllEqpInfoConfig();
                }
            }
        }

        private void btDeleteUnitInfoConfig_Click(object sender, EventArgs e)
        {
            if (!LftSem.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                if (this.LftSem.UserPrivilige)
                {
                    this.LftSem.LoginTimeCount = 1;
                }

                if (UIMessageDialog.ShowAskDialog(this.ParentForm, $"确认要删除参数名为{this.unitInfoConfigDgvSelectName}配置信息"))
                {
                    //删除Unit配置信息
                    this.DeleteUnitInfo();
                    this.LoadAllUnitInfoConfig();
                }
            }
        }
        /// <summary>
        /// 删除EQP参数信息
        /// </summary>
        private void DeleteEqpInfo()
        {
            if (!string.IsNullOrEmpty(this.eqpInfoConfigDgvSelectName))
            {
                string sqlString = $"DELETE FROM EQUIPMENTUDPROPERTY WHERE NAME = '{this.eqpInfoConfigDgvSelectName}'";
                DBConnection dBConnection = DBControl.GetConnection();
                try
                {
                    int returnCode = dBConnection.ExecuteUpdate(sqlString);
                    if (returnCode > 0)
                    {
                        UIMessageDialog.ShowSuccessDialog(this.ParentForm,"删除EQP参数信息成功，参数名字:" + this.eqpInfoConfigDgvSelectName);
                        LogHelper.operationLogger($"用户{this.LftSem.UserName}更新了EQP参数，参数名为:{this.eqpInfoConfigDgvSelectName}");
                    }
                    else
                    {
                        UIMessageDialog.ShowWarningDialog(this.ParentForm,"更新EQP参数信息失败，参数名字:" + this.eqpInfoConfigDgvSelectName);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.loggerError("更新EQP参数信息报错", ex);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
        }
        /// <summary>
        /// 删除Unit参数信息
        /// </summary>
        private void DeleteUnitInfo()
        {
            if (!string.IsNullOrEmpty(this.unitInfoConfigDgvSelectName) && !string.IsNullOrEmpty(this.unitInfoConfigDgvSelectEntityID))
            {
                string sqlString = $"DELETE FROM SUBSYSTEMUDPROPERTY WHERE NAME = '{this.unitInfoConfigDgvSelectName}' AND ENTITYID = '{this.unitInfoConfigDgvSelectEntityID}'";
                DBConnection dBConnection = DBControl.GetConnection();
                try
                {
                    int returnCode = dBConnection.ExecuteUpdate(sqlString);
                    if (returnCode > 0)
                    {
                        UIMessageDialog.ShowSuccessDialog(this.ParentForm, "删除Unit参数信息成功，参数名字:" + this.unitInfoConfigDgvSelectName);
                        LogHelper.operationLogger($"用户{this.LftSem.UserName}更新了Unit参数，参数名为:{this.unitInfoConfigDgvSelectName}");
                    }
                    else
                    {
                        UIMessageDialog.ShowWarningDialog(this.ParentForm, "更新Unit参数信息失败，参数名字:" + this.unitInfoConfigDgvSelectName);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.loggerError("更新Unit参数信息报错", ex);
                }
                DBControl.RemoveDBConection(dBConnection);
            }
        }
        private void eqpInfoConfigDgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            int index = e.RowIndex;
            try
            {
                if (this.eqpInfoConfigDgv.Rows[index].Cells[1].Value != null)
                {
                    this.eqpInfoConfigDgvSelectName = this.eqpInfoConfigDgv.Rows[index].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("选择参数信息报错，在btDeleteUnitInfoConfig_Click方法中", ex);
            }
        }

        private void unitInfoConfigDgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            int index = e.RowIndex;
            try
            {
                if (this.unitInfoConfigDgv.Rows[index].Cells[0].Value != null && this.unitInfoConfigDgv.Rows[index].Cells[1].Value != null)
                {
                    this.unitInfoConfigDgvSelectEntityID = this.unitInfoConfigDgv.Rows[index].Cells[0].Value.ToString();
                    this.unitInfoConfigDgvSelectName = this.unitInfoConfigDgv.Rows[index].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("选择参数信息报错，在btDeleteUnitInfoConfig_Click方法中", ex);
            }
        }
        #endregion

        /*        private void UITBConfig_Selecting(object sender, TabControlCancelEventArgs e)
                {
                    string tabPageName = e.TabPage.Name;
                    if ("AlarmConfig".Equals(tabPageName))
                    {
                        e.Cancel = AlarmConfigCancelFlag;
                    }
                    else if ("MenuConfig".Equals(tabPageName))
                    {
                        e.Cancel = MenuConfigCancelFlag;
                    }
                    else if ("SignalConfig".Equals(tabPageName))
                    {
                        e.Cancel = SignalConfigCancelFlag;
                    }
                }*/
    }
}
